package com.bitcoin.scheduler.service;

import io.github.jhipster.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class MailService {

    private final Logger log = LoggerFactory.getLogger(MailService.class);

    private final JHipsterProperties jHipsterProperties;

    private final JavaMailSender mailSender;

    private final SpringTemplateEngine templateEngine;

    public MailService(JHipsterProperties jHipsterProperties, JavaMailSender mailSender,
                       SpringTemplateEngine templateEngine) {

        this.jHipsterProperties = jHipsterProperties;
        this.mailSender = mailSender;
        this.templateEngine = templateEngine;
    }

//    @Async
    public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {

        // Prepare message using a Spring helper
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content, isHtml);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public void tableMonitorEmail(String subject, String toUser, Map parameter) {
        Context context = new Context();
        context.setVariable("content", parameter);
        try {
            String content = templateEngine.process("email/tableMonitorEmail", context);
            sendEmail(toUser, subject, content, false, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
